﻿using System.Collections.Generic;
using Coding4Fun.Cannon.Wcf;
using Coding4Fun.Cannon.Web.Common;

namespace Coding4Fun.Cannon.Web.Betty
{
	public class BettyHandler : CommonHttpHandler
	{
		static DriveService _driveService;
		static AimService _aimService;
		static ShootService _shootService;
		static SettingsService _settingsService;

		static void CheckServiceCreation()
		{
			if (_aimService == null)
				_aimService = new AimService();

			if (_driveService == null)
				_driveService = new DriveService();

			if (_shootService == null)
				_shootService = new ShootService();

			if (_settingsService == null)
				_settingsService = new SettingsService();
		}


		public override void Aim(double pan, double tilt)
		{
			CheckServiceCreation();

			_aimService.SetPanAndTiltAngles(pan, tilt);
		}

		public override void AimTilt(double value)
		{
			CheckServiceCreation();

			_aimService.SetTiltAngle(value);
		}

		public override void AimPan(double value)
		{
			CheckServiceCreation();

			_aimService.SetPanAngle(value);
		}

		public override void Drive(int leftPower, int rightPower)
		{
			CheckServiceCreation();

			_driveService.SetPowerByMotor(leftPower, rightPower);
		}

		public override void Drive(int power)
		{
			CheckServiceCreation();

			_driveService.SetPower(power);
		}

		public override void Fire()
		{
			CheckServiceCreation();

			_shootService.Fire();
		}

		public override Dictionary<string, double> Initialize()
		{
			CheckServiceCreation();

			var panMin = _settingsService.GetAimPanMinAngle();
			var panMax = _settingsService.GetAimPanMaxAngle();

			var tiltMin = _settingsService.GetAimTiltMinAngle();
			var tiltMax = _settingsService.GetAimTiltMaxAngle();

			_aimService.Reset();
			_driveService.Stop();

			return new Dictionary<string, double> {
				{"PanMin", panMin}, 
				{"PanMax", panMax},
				{"TiltMin", tiltMin}, 
				{"TiltMax", tiltMax},
			};
		}
	}
}